package jpaperwork.meta.transformer;

import jpaperwork.meta.descriptor.*;
import jpaperwork.meta.transformer.path.Path;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

public class JSONFormBuilder implements FormBuilder {

    public Object buildFlat(Path path, Flat flat, Object transformee) {
        System.out.println(path.toString());
        return transformee;
    }

    public Object buildForm(Path path, Form form, List<FieldValue> transformedFields) {
        System.out.println(path.toString());
        JSONObject object = new JSONObject();
        for (FieldValue fieldValue : transformedFields) {
            try {
                object.put(fieldValue.getField().getName(), fieldValue.getValue());
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }
        return object;
    }

    public Object buildCollection(Path path, Aggregation aggregation, List transformedValues) {
        System.out.println(path.toString());
        JSONArray array = new JSONArray();
        for (Object o : transformedValues) {
            array.put(o);
        }

        return array;
    }

    public Object buildPolymorhpic(Path path, Polymorphism polymorphism, DiscriminatedType actualType, Object transformedValue) {
        System.out.println(path.toString());
        try {
            ((JSONObject)transformedValue).put("_TYPE_", actualType.getDiscriminator());
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

        return transformedValue;
    }
}
